// Device/pages/Info/components/glucometer-component/index.js

const app = getApp();
import {
    customNavigate
} from '@/utils/route';
import {
    showToast
} from '@/utils/util';
import {
    fetchUpdateSugar
} from '@/services/device';
const userTagState = {
    '本人': 'self',
    '配偶': 'mate',
    '子女': 'sons',
    '其他': 'other'
}
const measurementTypeState = {
    '餐前': 'glu',
    '餐后': 'pbg'
}
const statusMappings = {
    1: '在线',
    0: '离线'
}
const options = {
    本人: ['餐前', '餐后'],
    配偶: ['餐前', '餐后'],
    子女: ['餐前', '餐后'],
    其他: ['餐前', '餐后']
};
Component({
    /**
     * 组件的初始数据
     */
    data: {
        show: false,
        deviceData: [],
        staticPrefix: app.globalData.STATIC_PREFIX,
        columns: [{
                values: Object.keys(options),
                className: 'column1',
            },
            {
                values: options['本人'],
                className: 'column2',
                defaultIndex: 0,
            },
        ],
    },
    /**
     * 组件的属性列表
     */
    properties: {
        deviceInfo: {
            type: Object,
            value: {}
        }
    },
    observers: {
        deviceInfo(value) {
            const {
                blood_sugars,
                blood_sugar_info
            } = value;
            const record = blood_sugars?.[0] || {};
            const {
                measurement_type = '', user_tag = '', blood_glucose_val = 0
            } = record;
            console.log(measurement_type, user_tag)
            const min = blood_sugar_info?.[`${measurementTypeState[measurement_type]}_min_${userTagState[user_tag]}`] || 0;
            const max = blood_sugar_info?.[`${measurementTypeState[measurement_type]}_max_${userTagState[user_tag]}`] || 0;
            let state;
            if (measurement_type && user_tag) {
                if (blood_glucose_val > max) {
                    state = '高血糖告警';
                } else if (blood_glucose_val < min) {
                    state = '低血糖告警';
                } else {
                    state = '正常血糖';
                }
            } else {
                state = '正常血糖'
            }
            const data = new Map([
                ['device_status', '联网状态'],
                ['signal_strength', '信号强度']
            ]);
            let obj = {
                device_status: statusMappings[value['device_status']],
                signal_strength: value['signal_strength'] || '--'
            }
            let result = [];
            for (let [key, value] of Object.entries(obj)) {
                result.push({
                    key: data.get(key),
                    value,
                    path: '/Device/pages/Analysis/index?type=' + key
                })
            }
            this.setData({
                deviceData: result,
                state,
                record,
                min,
                max
            });
        }
    },
    methods: {
        onTap() {
            this.setData({
                show: true
            })
        },
        onNavigate() {
            const {
                device_type,
                product_type,
                device_imei
            } = this.data.deviceInfo;
            const params = {
                device_type,
                product_type,
                device_imei
            }
            customNavigate({
                url: `/Device/pages/History/index`,
                params
            })
        },
        onNavigateToAnalysis() {
            customNavigate({
                url: '/Device/pages/Analysis/index',
                params: {
                    device_imei: this.data.deviceInfo.device_imei
                }
            })
        },
        onCancel() {
            this.setData({
                show: false
            })
        },
        async onConfirm(e) {
            console.log(e)
            const params = {
                user_tag: e.detail.value[0],
                measurement_type: e.detail.value[1],
                id: this.data.record.id
            }
            const res = await fetchUpdateSugar(params);
            if (res.return_code == 'SUCCESS') {
                showToast('认领成功！', () => {
                    this.refreshPage()
                })
            }
        },
        refreshPage() {
            console.log("重新加载页面");
            const currentPage = getCurrentPages().pop(); // 获取当前页面实例
            if (currentPage) {
                const options = currentPage.options; // 获取页面参数
                wx.redirectTo({
                    url: `/${currentPage.route}?${this.getQueryString(options)}`
                });
            }
        },

        // 辅助函数：将参数对象转换为查询字符串
        getQueryString(options) {
            return Object.keys(options)
                .map(key => `${key}=${options[key]}`)
                .join("&");
        }
    }
})